package familytree.yu.com.sso.config;

import familytree.yu.com.sso.config.jwt.Oauth2JwtTokenEnhancer;
import familytree.yu.com.sso.oauth2.PasswordCodeTokenGranter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: yuyunbo
 * @Date: 2021/2/23 20:30
 * @Description:
 */
@Configuration
@EnableAuthorizationServer
public class Oauth2AuthenticationServer extends AuthorizationServerConfigurerAdapter {


    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @Resource
    private TokenStore tokenStore;

    @Resource
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Resource
    private Oauth2JwtTokenEnhancer oauth2JwtTokenEnhancer;


    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private WebResponseExceptionTranslator webResponseExceptionTranslator;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("isAuthenticated()");
        //允许客户端使用表单方式发送请求token的认证（因为表单一般是POST请求，所以使用POST方式发送获取token，但必须携带clientId，clientSecret，否则随便一请求过来验token是不验的）
        security.allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        super.configure(clients);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancerList = new ArrayList<>();
        //配置JWT的内容增强器
        enhancerList.add(oauth2JwtTokenEnhancer);
        enhancerList.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(enhancerList);

        //初始化
        endpoints.accessTokenConverter(jwtAccessTokenConverter)
                //设置将token存储在JWT中
                .tokenStore(tokenStore)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                //认证异常处理器
                .exceptionTranslator(webResponseExceptionTranslator)
                .reuseRefreshTokens(true)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .tokenEnhancer(enhancerChain);

        endpoints.pathMapping("/oauth/token", "/oauth/token");
        PasswordCodeTokenGranter passwordCodeTokenGranter = new PasswordCodeTokenGranter(endpoints.getTokenServices(),
                endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory(), userDetailsService, bCryptPasswordEncoder);
        CompositeTokenGranter compositTokenGrant =
                new CompositeTokenGranter(Arrays.asList(endpoints.getTokenGranter(), passwordCodeTokenGranter));
        endpoints.tokenGranter(compositTokenGrant);
    }
}
